<template>
  <div class="page-class">
    <Breadcrumb>
      <a-button type="primary" @click="handleAdd">新增</a-button>
    </Breadcrumb>
    <div class="cnt-class">
      <div class="query">
        <a-row>
          <a-col :span="6">
            <a-input-search
              v-model.trim="query.queryValue"
              :maxLength="50"
              allowClear
              placeholder="请输入创建人或投票主题"
              @search="onSearch"
            >
              <a-button slot="enterButton" type="primary"> 搜索 </a-button>
            </a-input-search>
          </a-col>
        </a-row>
        <!-- 筛选列表 -->
        <Collapse :opend="opend" @changOpend="changOpend">
          <a-row>
            <a-col :span="24">
              <span class="collapse-label">状态：</span>
              <a-radio-group v-model="query.status">
                <a-radio
                  v-for="(node, index) in stateList"
                  :value="node.value"
                  :key="index"
                >
                  {{ node.name }}
                </a-radio>
              </a-radio-group>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="24">
              <span class="collapse-label">选项类型：</span>
              <a-radio-group v-model="query.selectType">
                <a-radio
                  v-for="(node, index) in selectList"
                  :value="node.value"
                  :key="index"
                >
                  {{ node.name }}
                </a-radio>
              </a-radio-group>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="24">
              <a-button type="primary" @click="getList(2)">查询</a-button>
              <a-button type="default" @click="handleRest">重置</a-button>
            </a-col>
          </a-row>
        </Collapse>
      </div>
      <div class="table">
        <BaseTable
          ref="table"
          rowKey="contentId"
          :scroll="{ x: 800, y: y }"
          :loading="loading"
          :columns="columns"
          :dataSource="list"
          :hideSelect="false"
          :selectedRowKeys="selectedRowKeys"
          @deleteRows="handleDelete"
          @selectChange="selectChange"
          @change="getList"
        ></BaseTable>
      </div>
    </div>
    <!-- 发布声明 -->
    <Statement
      :visible="statement.visible"
      :row="statement.row"
      @close="handleClose"
    ></Statement>
  </div>
</template>
<script>
import BaseTable from "@/components/BaseTable";
import Collapse from "@/components/Collapse";
import Statement from "./compoments/Statement";
import httpApi from "@/api/vote";
import { stateList, selectList, voteUpdateType } from "@/utils";

export default {
  components: {
    BaseTable,
    Collapse,
    Statement
  },
  data() {
    return {
      opend: true,
      loading: false,
      time: -1,
      statement: {
        visible: false,
        row: {}
      },
      query: {
        status: undefined,
        selectType: undefined,
        queryValue: undefined
      },
      list: [],
      selectedRowKeys: [],
      stateList,
      selectList,
      columns: [
        {
          title: "投票主题",
          dataIndex: "subject",
          width: 240
        },
        {
          title: "选项类型",
          dataIndex: "selectType",
          width: 120,
          customRender: (type) => {
            let node = selectList.find((v) => v.value === type);
            return node.name || "--";
          }
        },
        {
          title: "投票类型",
          dataIndex: "voteUpdateType",
          width: 160,
          customRender: (type) => {
            let node = voteUpdateType.find((v) => v.value === type);
            return node.name || "--";
          }
        },
        {
          title: "投票结果",
          dataIndex: "result",
          width: 120,
          customRender(data) {
            return data || "--";
          }
        },
        {
          title: "推动范围",
          dataIndex: "result",
          width: 120,
          customRender(data) {
            return data || "--";
          }
        },
        {
          title: "上限人数",
          width: 120,
          customRender(v, row) {
            if (!row.maxUserNum) return "不限";
            return row.maxUserNum + "人";
          }
        },
        {
          title: "目标户数",
          width: 120,
          dataIndex: "order",
          customRender(data) {
            return data || "--";
          }
        },
        {
          title: "已认证",
          width: 120,
          dataIndex: "order",
          customRender(data) {
            return data || "--";
          }
        },
        {
          title: "参与人数",
          dataIndex: "joinNumber",
          width: 120,
          customRender(type) {
            return type + "人";
          }
        },
        {
          title: "状态",
          width: 100,
          dataIndex: "voteStatus",
          customRender: (type) => {
            let node = stateList.find((v) => v.value === type);
            return node.name || "--";
          }
        },
        {
          title: "创建人",
          width: 120,
          dataIndex: "createrUserName",
          customRender(type) {
            return type || "--";
          }
        },
        {
          title: "创建时间",
          width: 120,
          dataIndex: "createTime",
          customRender(type) {
            return type || "--";
          }
        },
        {
          title: "截至时间",
          width: 120,
          dataIndex: "endTime",
          customRender(type) {
            return type || "--";
          }
        },
        {
          title: "发布人",
          width: 120,
          customRender(v, row) {
            return row.voteStatus === 2 || row.voteStatus === 4
              ? row.operatorUserName
              : "--";
          }
        },
        {
          title: "发布时间",
          width: 120,
          customRender(v, row) {
            return row.voteStatus === 2 || row.voteStatus === 4
              ? row.upadteTime
              : "--";
          }
        },
        {
          title: "撤回人",
          width: 120,
          customRender(v, row) {
            return row.voteStatus === 3 ? row.operatorUserName : "--";
          }
        },
        {
          title: "撤回时间",
          width: 120,
          dataIndex: "upadteTime",
          customRender(v, row) {
            return row.voteStatus === 3 ? row.upadteTime : "--";
          }
        },
        {
          title: "操作",
          width: 280,
          fixed: "right",
          customRender: (v, row) => {
            // 1 未发布 2 已发布  3 已撤回 4 已结束
            // 无人参与投票，撤回后可编辑重新发布。有人参与投票，撤回后仅支持查看
            if (row.voteStatus === 1) {
              return (
                <div class="operate-td">
                  <a onClick={() => this.handleShow(row)}>查看</a>
                  <a-divider type="vertical" />
                  <a onClick={() => this.handleEdit(row)}>编辑</a>
                  <a-divider type="vertical" />
                  <a onClick={() => this.handlePublish(row)}>发布</a>
                  <a-divider type="vertical" />
                  <a onClick={() => this.handleDelete(row)}>删除</a>
                </div>
              );
            } else if (row.voteStatus === 2) {
              // 目标户数 !== 参与人数   显示 ‘导出未参与’
              return (
                <div class="operate-td">
                  <a onClick={() => this.handleShow(row)}>查看</a>
                  <a-divider type="vertical" />
                  <a onClick={() => this.handlePrex(row)}>撤回</a>
                  <a-divider type="vertical" />
                  <a onClick={() => this.handleSendMsg(row)}>短信提醒 </a>
                  <a-divider type="vertical" />
                  <a onClick={() => this.handleExportUnjoin(row)}>导出未参与</a>
                </div>
              );
            } else if (row.voteStatus === 3) {
              if (row.joinNumber) {
                return (
                  <div class="operate-td">
                    <a onClick={() => this.handleShow(row)}>查看</a>
                    <a-divider type="vertical" />
                    <a onClick={() => this.handleDelete(row)}>删除</a>
                  </div>
                );
              } else {
                return (
                  <div class="operate-td">
                    <a onClick={() => this.handleShow(row)}>查看</a>
                    <a-divider type="vertical" />
                    <a onClick={() => this.handleEdit(row)}>编辑</a>
                    <a-divider type="vertical" />
                    <a onClick={() => this.handlePublish(row)}>发布</a>
                    <a-divider type="vertical" />
                    <a onClick={() => this.handleDelete(row)}>删除</a>
                  </div>
                );
              }
            } else {
              // 目标户数 !== 参与人数   显示 ‘导出未参与’
              return (
                <div class="operate-td">
                  <a onClick={() => this.handleShow(row)}>查看</a>
                  <a-divider type="vertical" />
                  <a onClick={() => this.handleStatement(row)}>发布声明</a>
                  <a-divider type="vertical" />
                  <a onClick={() => this.handleExportUnjoin(row)}>导出未参与</a>
                </div>
              );
            }
          }
        }
      ]
    };
  },
  computed: {
    y() {
      return this.opend ? 330 : 480;
    }
  },
  mounted() {
    this.getList();
  },
  methods: {
    handleExportUnjoin(row) {
      //导出未参与
      console.log(row);
      this.$confirm({
        title: "导出",
        content: "是否确定导出未参与的数据？",
        onOk: () => {
          httpApi
            .deleteRows()
            .then((res) => {
              if (res.retcode === 0) {
                this.$message.success("导出成功！");
              } else {
                this.$message.error(res.msg || "导出失败！");
              }
            })
            .catch((err) => {
              this.$message.error(err.msg || "导出失败！");
            });
        },
        onCancel: () => {
          console.log("已取消删除操作");
        }
      });
    },
    handleStatement(row) {
      //发布声明
      this.statement = {
        visible: true,
        row: row
      };
    },
    handleClose() {
      this.statement = {
        visible: false,
        row: {}
      };
    },
    handleSendMsg(row) {
      //短信提醒
      console.log(row);
      // 人数：目标户数 - 参与人数
      let title = "短信提醒";
      let content = `是否对推送范围内的业主发送短信提醒投票，共计0人？`;

      this.$confirm({
        title,
        content,
        onOk: () => {
          httpApi
            .deleteRows()
            .then((res) => {
              if (res.retcode === 0) {
                this.$message.success("短信提醒成功！");
                this.getList();
              } else {
                this.$message.error(res.msg || "短信提醒失败！");
              }
            })
            .catch((err) => {
              this.$message.error(err.msg || "短信提醒失败！");
            });
        },
        onCancel: () => {
          console.log("已取消删除操作");
        }
      });
    },
    changOpend(opend) {
      this.opend = opend;
    },
    onSearch() {
      clearTimeout(this.time);
      this.time = setTimeout(() => {
        this.getList(null, 1);
      }, 600);
    },
    getList(type, current) {
      this.loading = true;
      if (current === 1) {
        this.$refs.table.pageInfo.current = 1;
      }

      let data = {
        pageNo: this.$refs.table.pageInfo.current,
        pageSize: this.$refs.table.pageInfo.pageSize
      };

      if (type === 2) {
        //查询
        data.status = this.query.status;
        data.selectType = this.query.selectType;
      } else {
        data.queryValue = this.query.queryValue;
      }

      httpApi
        .getList(data)
        .then((res) => {
          if (res.retcode === 0) {
            this.list = res.data.records || [];
            if (this.$refs.table) {
              this.$refs.table.pageInfo.total = res.data.total;
            }
          } else {
            this.$message.error(res.msg);
          }
          this.loading = false;
        })
        .catch((err) => {
          this.$message.error(err.msg);
          this.loading = false;
        });
    },
    handleAdd() {
      this.$router.push({
        path: "/vote/add",
        query: {
          type: "1"
        }
      });
    },
    handleEdit(row) {
      // 编辑
      this.$router.push({
        path: "/vote/edit",
        query: {
          id: row.contentId,
          type: "2"
        }
      });
    },
    handleShow(row) {
      // 查看
      this.$router.push({
        path: "/vote/detail",
        query: {
          id: row.contentId
        }
      });
    },
    handleRest() {
      // 重置
      this.query.status = undefined;
      this.query.selectType = undefined;
    },
    handlePublish(row) {
      //发布
      this.$confirm({
        title: "发布",
        content: () => <div class="pwd-msg">是否立即发布投票活动？</div>,
        onOk: () => {
          httpApi
            .updateStatus({
              status: 2,
              voteContentId: row.contentId
            })
            .then((res) => {
              if (res.retcode === 0) {
                this.$message.success("发布成功！");
                this.getList();
              } else {
                this.$message.error("发布失败！");
              }
            })
            .catch((err) => {
              this.$message.error(err.msg || "发布失败！");
            });
        },
        onCancel: () => {}
      });
    },
    handlePrex(row) {
      this.$confirm({
        title: "撤回",
        content: () => (
          <div>
            <div class="pwd-msg">是否立即撤回投票活动？</div>
            <span class="pwd-tip">
              无人参与投票，撤回后可编辑重新发布。有人参与投票，撤回后仅支持查看
            </span>
          </div>
        ),
        onOk: () => {
          httpApi
            .updateStatus({
              status: 3,
              voteContentId: row.contentId
            })
            .then((res) => {
              if (res.retcode === 0) {
                this.$message.success("撤回成功！");
                this.getList();
              } else {
                this.$message.error("撤回失败！");
              }
            })
            .catch((err) => {
              this.$message.error(err.msg || "撤回失败！");
            });
        },
        onCancel: () => {}
      });
    },
    handleDelete(row) {
      let title = "";
      let content = "";
      let ids = [];
      if (row) {
        ids = [row.contentId];
        title = "删除：";
        content = "是否删除投票活动?";
      } else {
        ids = this.selectedRowKeys;
        title = "批量删除：";
        content = `是否删除已选中的 ${ids.length} 项投票活动？`;
      }

      this.$confirm({
        title,
        content,
        onOk: () => {
          httpApi
            .deleteRows(ids)
            .then((res) => {
              if (res.retcode === 0) {
                this.$message.success("删除成功！");
                this.getList();
              } else {
                this.$message.error(res.msg || "删除失败！");
              }
            })
            .catch((err) => {
              this.$message.error(err.msg || "删除失败！");
            });
        },
        onCancel: () => {
          console.log("已取消删除操作");
        }
      });
    },
    selectChange(selectedKeys) {
      this.selectedRowKeys = selectedKeys;
    }
  }
};
</script>
<style scoped lang="less">
.pwd-tip {
  display: inline-block;
  margin-top: 10px;
  .font-Medium(12px, #f5222d, 18px, 400);
}
</style>
